import folium
import webbrowser
import time
from selenium import webdriver
import socket
import time
import json
import pymysql

i = -1
loc = []
print("服务端开启")
# 套接字接口
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置IP和端口
host = '192.168.137.1'
port = 8001
# bind绑定该端口
mySocket.bind((host, port))
mySocket.listen(10)

# 接收客户端连接
print("等待连接....")
client, address = mySocket.accept()
print("新连接")
print("IP is %s" % address[0])
print("port is %d\n" % address[1])


def msg():
    # 读取消息
    msg = json.loads(client.recv(1024))
    ##msg = client.recv(1024)
    # 把接收到的数据进行解码
    lon = msg[0]
    lat = msg[1]
    print("lat:", msg[0], "\t lon:", msg[1])
    print("accx:{} accy:{} accz:{}".format(msg[2], msg[3], msg[4]))
    print("gyrx:{} gyry:{} gyrz:{}".format(msg[5], msg[6], msg[7]))
    print("magx:{} magy:{} magz:{}".format(msg[8], msg[9], msg[10]))
    print("######################")
    return [lon, lat]


def draw_gps(map_file_name,i):
    """
    绘制gps轨迹图
    :param locations: list, 需要绘制轨迹的经纬度信息，格式为[[lat1, lon1], [lat2, lon2], ...]
    :param output_path: str, 轨迹图保存路径
    :param file_name: str, 轨迹图保存文件名
    :return: None
    """
    i += 1
    loc.append(msg())
    m = folium.Map(loc[0],  # 中心区域的确定
                   zoom_start=20,
                   tiles="http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
                   # 设置高德底图
                   attr='default')

    folium.PolyLine(  # polyline方法为将坐标用线段形式连接起来
        loc,  # 将坐标点连接起来
        weight=3,  # 线的大小为3
        color='orange',  # 线的颜色为橙色
        opacity=0.8  # 线的透明度
    ).add_to(m)  # 将这条线添加到刚才的区域m内

    # 起始点，结束点
    folium.Marker(loc[0], popup='<b>Starting Point</b>').add_to(m)
    folium.Marker(loc[i], popup='<b>End Point</b>').add_to(m)
    m.save(map_file_name)  # 将结果以HTML形式保存到指定路径

##def g_connect(i):
if __name__ == "__main__":

    print("服务端开启")
    # 套接字接口
    mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 设置IP和端口
    host = '192.168.137.1'
    port = 2222
    # bind绑定该端口
    mySocket.bind((host, port))
    mySocket.listen(10)

    chrome_drive = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
    driver = webdriver.Chrome(executable_path=chrome_drive)
    msg()
    draw_gps('map.html', i)
    driver.set_window_size(840, 640)  # 设置浏览器大小
    ##  locations[0] = msg()
    driver.get('file:///D:/anaconda3/envs/pythonWork/gps/map.html')

    # 打开数据库连接
    db = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        passwd='1842',
        db='wooden',
        charset='utf8'
    )
    print("数据库开启")
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    sqltime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

    # 接收客户端连接
    print("等待连接....")
    client, address = mySocket.accept()
    print("新连接")
    print("IP is %s" % address[0])
    print("port is %d\n" % address[1])
    while True:
    # 读取消息
    #     udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #     # 绑定本地相关信息，如果不绑定，则系统会随机分配，必须绑定本电脑的ip和port
    #     local_addr = ('192.168.137.1', 2222)  # 元组的第一个参数为本机IP，可以为空字符串，会自动生成本机IP
    #     udp_socket.bind(local_addr)
        # 等待接收方发送数据
        # rs中存储的是一个元组（接收到的数据，（发送方的ip，port））
        msg= json.loads(client.recv(1024))
        # rs_masg, rs_addr = udp_socket.recvfrom(2048)
        #rs_data = rs_data.decode("utf-8")
        #print(msg)
        lon = msg[0]
        lat = msg[1]
        print("lat:", lon, "\t lon:", lat)
        print("accx:{} accy:{} accz:{}".format(msg[2], msg[3], msg[4]))
        print("gyrx:{} gyry:{} gyrz:{}".format(msg[5], msg[6], msg[7]))
        print("magx:{} magy:{} magz:{}".format(msg[8], msg[9], msg[10]))
        print("######################")
        draw_gps('map.html', i)
        driver.refresh()  # 刷新页面
        print('刷新页面')
    #SQL 插入语句
    sql = "INSERT INTO MAGNETISM(MTIME , MFLAG) VALUES ('%s','%s')" % (sqltime, msg.decode("utf-8"))
    sql = "insert into bd(id,lon,lat)values('%d','%f','%f')" % (
        i, lon, lat)
        try:
            while True:
            # # 查询

        except Exception as e:
            print('test fail')
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except BaseException:
        # 如果发生错误则回滚
        db.rollback()

        if rs_data == "over":
            #client.close()
            # mySocket.close()
            # # 关闭数据库连接
            # db.close()
            print("程序结束\n")
            exit()
